/*
 * @Author: shiguo
 * @Date: 2022-04-24 14:27:02
 * @LastEditors: shiguo
 * @LastEditTime: 2022-12-21 15:36:06
 * @FilePath: /@aks-dev/easyui/lib/Hud/PopoverView/PopoverView.tsx
 */
import React, { useImperativeHandle, useState } from 'react';
import { StyleSheet, TouchableOpacity, BackHandler } from 'react-native';
import type {PopoverViewOptions } from '.';






export const PopoverView = React.forwardRef<PopoverViewOptions.RefAttributes, {}>((_, ref) => {
    const [visible, setVisible] = useState<boolean>(false);
    const [options, setOptions] = useState<Partial<PopoverViewOptions> | undefined>()

    React.useEffect(() => {
        const onBackPress = () => visible;
        BackHandler.addEventListener('hardwareBackPress', onBackPress);
        return () => BackHandler.removeEventListener('hardwareBackPress', onBackPress);
    }, [visible])


    useImperativeHandle<unknown, PopoverViewOptions.RefAttributes>(ref, () => ({
        showPopoverView: (options: Partial<PopoverViewOptions>) => {
            setVisible(true);
            setOptions(options)

        },
        hidePopoverView: () => {
            setVisible(false);
            setOptions(undefined)
        }
    }), [visible])

    if (!visible)
        return null;

    return (
        <TouchableOpacity activeOpacity={1} style={[styles.container, options?.style]} disabled={options?.disabled} onPress={e => {
            setVisible(false);
            setOptions(undefined)
            // e.stopPropagation()
        }}>
            {React.isValidElement(options?.content) && options?.content}
        </TouchableOpacity>
    )
})

export const popoverViewRef = React.createRef<PopoverViewOptions.RefAttributes>();
export const showPopoverView = (options: Partial<PopoverViewOptions>) => popoverViewRef.current?.showPopoverView(options)
export const hidePopoverView = () => popoverViewRef.current?.hidePopoverView()


const styles = StyleSheet.create({
    container: {
        ...StyleSheet.absoluteFillObject,
        display: 'flex',
        
        // backgroundColor:'red'
    },
})
